// pages/settings/settings.js
Page({
  data: {
    userInfo: null,
    baseUrl: 'http://localhost:3000'
  },

  onLoad: function() {
    this.loadUserInfo();
  },

  onShow: function() {
    this.loadUserInfo();
  },

  // 加载用户信息
  loadUserInfo: function() {
    const userInfo = wx.getStorageSync('userInfo');
    if (userInfo) {
      this.setData({ userInfo });
    }
  },

  // 切换角色
  switchRole: function(e) {
    const { role } = e.currentTarget.dataset;
    const { userInfo } = this.data;

    if (userInfo.role === role) {
      return;
    }

    wx.showModal({
      title: '确认切换身份',
      content: `确定要切换为${role === 'student' ? '学生/校友' : '企业用户'}吗？`,
      success: (res) => {
        if (res.confirm) {
          wx.showLoading({
            title: '切换中...'
          });

          wx.request({
            url: `${this.data.baseUrl}/api/users/${userInfo.id}/role`,
            method: 'PUT',
            data: { role },
            success: (res) => {
              wx.hideLoading();
              if (res.data.success) {
                userInfo.role = role;
                wx.setStorageSync('userInfo', userInfo);
                this.setData({ userInfo });

                wx.showToast({
                  title: '切换成功',
                  icon: 'success'
                });

                // Navigate back to profile page and then to jobs page
                wx.navigateBack({
                  delta: 1,
                  complete: () => {
                    setTimeout(() => {
                      wx.switchTab({
                        url: '/pages/jobs/jobs'
                      });
                    }, 500); // Add a small delay to ensure the navigation completes
                  }
                });
              }
            },
            fail: () => {
              wx.hideLoading();
              wx.showToast({
                title: '切换失败',
                icon: 'none'
              });
            }
          });
        }
      }
    });
  }
});